import random
from socket import timeout
import threading
import cv2
from frida.core import Device
import numpy as np
from lamda.client import *
from PIL import Image
import io
import time
import xml.etree.ElementTree as ET
import os



def get_target_hole_position_no_display(image_path):
    """
    计算图片中目标缺口位置，并保存处理后的图片，不进行实时显示。
    """
    img = cv2.imread(image_path)
    if img is None:
        print(f"错误: 无法加载图片 '{image_path}'")
        return None

    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    edges = cv2.Canny(gray, 100, 200)
    contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    potential_holes_x = []
    for contour in contours:
        area = cv2.contourArea(contour)
        # print(f"面积:{area}")
        if 10000 < area < 20000:
            M = cv2.moments(contour)
            if M["m00"] != 0:
                cx = int(M["m10"] / M["m00"])
                potential_holes_x.append(cx)

    return max(potential_holes_x)

def saveImg(d):
    
    backgroundUI = d(resourceId = "captcha-verify-image")
    output_filename = "backgroundImg.png"
    backgroundimg = backgroundUI.screenshot(quality=100).save(output_filename)
    return output_filename

def move(d, sp):
    slideUI = d(className="android.widget.Image").get(1)
    sx = ((slideUI.get(1).info().bounds.left)+(slideUI.get(1).info().bounds.right)) // 2 
    # print("sx:",sx)
    sy = ((slideUI.get(1).info().bounds.top)+(slideUI.get(1).info().bounds.bottom)) // 2

    calibration_offset = 137  
    end_x = sp + calibration_offset
    
    # 计算需要滑动的总距离
    total_move_distance = end_x - sx

    print(f"滑块起始坐标: ({sx}, {sy})")
    print(f"识别出的缺口坐标: {sp}px")
    print(f"校准后的目标终点X坐标: {end_x}px")
    print(f"需要滑动的总距离: {total_move_distance}px")

    # 安全检查：如果计算出的距离过小或为负，说明可能出错了，避免无效操作
    if total_move_distance <= 10:
        print("警告: 计算出的滑动距离过小，操作可能无效或已在目标位置。")
        return
    print("开始滑动")
    touch = TouchBuilder().down(x=sx, y=sy,pressure=random.randint(50,70)).wait(random.randint(150, 250))
    steps = random.randint(6, 9)
    for i in range(steps):
        progress = (i + 1) / steps
        ease_out_progress = 1 - (1 - progress) ** 3
        current_step_x = sx + total_move_distance * ease_out_progress
        random_y_offset = random.randint(-8, 8)
        wait_ms = random.randint(100, 400)
        touch.move(x=int(current_step_x), y=sy + random_y_offset,pressure=random.randint(50,70)).wait(wait_ms)
        
    # 模拟人为拖动超出距离再拖回来
    overshoot_x = end_x + random.randint(4, 10)
    touch.move(x=overshoot_x, y=sy + random.randint(-5, 5),pressure=random.randint(50,70)).wait(random.randint(700, 900))
    touch.move(x=end_x, y=sy + random.randint(-2, 2),pressure=random.randint(50,70)).wait(random.randint(500, 900))
    touch.up()
    d.perform_touch(touch.build())
    
    print("滑动操作执行完毕。")
    return

def check_verifyCode(d):
    captcha = d(resourceId="captcha-verify-image")
    if captcha.exists():
        print("出现验证码开始处理")
        load = d(resourceId = "com.zhiliaoapp.musically:id/h3f")
        output_file = f'handle.png' 
        for i in range(5):
            if  not load.exists():
                image_file = saveImg(d)
                x = get_target_hole_position_no_display(image_file)
                move(d,x)
                print("滑动成功")
                return True
            else:  
                time.sleep(10)
                print(f"尝试等待第{i}次")     
        else:
            time.sleep(5)
            back = d(resourceId = "com.android.systemui:id/back")
            print("出现网络问题，一直在加载，开始点击返回")
            back.click()
            return False
    else:
        return False


if __name__ == "__main__":
    d = Device("192.168.12.4",65008)
    check_verifyCode(d)
